package com.example.designpatternproject.wrapper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


/**
 * @ClassName: WrapperAdapter
 * @Author: 史大拿
 * @CreateDate: 10/19/22$ 3:47 PM$
 * TODO
 */
public class WrapperAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context mContext;
    // 原始adapter
    private final RecyclerView.Adapter originAdapter;

    // 头布局
    private final LinearLayout headView;

    // 尾布局
    private final LinearLayout footView;

    public WrapperAdapter(Context context, RecyclerView.Adapter adapter) {
        mContext = context;
        originAdapter = adapter;
        if(originAdapter == null){
            throw new RuntimeException("adapter = null.");
        }

        headView = new LinearLayout(context);
        headView.setOrientation(LinearLayout.VERTICAL);
        footView = new LinearLayout(context);
        footView.setOrientation(LinearLayout.VERTICAL);
        originAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                // 当适配器发生改变的时候调用
                super.onChanged();
                notifyDataSetChanged();
            }
        });
    }

    // 将位置作为viewType
    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int position) {
        Log.i("szjViewType", position + "");

        if (isHeadView() && position == 0) {
            // 头布局
            return createViewHolder(headView);
        }

        // 中间布局
        int adjPosition;

        // 是否有头布局
        if (isHeadView()) {
            adjPosition = position - 1;
        } else {
            adjPosition = position;
        }

        int adapterCount;
        if (originAdapter != null) {
            adapterCount = originAdapter.getItemCount();
            if (adjPosition < adapterCount) {
                return originAdapter.onCreateViewHolder(parent, originAdapter.getItemViewType(adjPosition));
            }
        }

        // 尾布局
        return createViewHolder(footView);
    }

    /*
     * 作者:史大拿
     * 创建时间: 10/20/22 9:25 AM
     * TODO 是否有headView
     */
    public boolean isHeadView() {
        return headView.getChildCount() > 0;
    }

    private RecyclerView.ViewHolder createViewHolder(View view) {
        return new TempViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        if (isHeadView() && position == 0) {
            holder.itemView.setOnTouchListener(new OnWrapperClickListener(TYPE.HEAD, holder.itemView, position, 0));
            return;
        }

        final int adjPosition;
        // 是否有头布局
        if (isHeadView()) {
            adjPosition = position - 1;
        } else {
            adjPosition = position;
        }
        int adapterCount = 0;
        if (originAdapter != null) {
            adapterCount = originAdapter.getItemCount();
            Log.i("szjCenterCount", position + "\tadjPosition" + adjPosition + "\tadapterCount:" + adapterCount + "\tholder:" + holder.getClass().getSimpleName());

            if (adjPosition <= adapterCount && !(holder instanceof TempViewHolder)) {

                originAdapter.onBindViewHolder(holder, adjPosition);
                int tempPosition;
                if (isHeadView()) { // 有head
                    tempPosition = position + headView.getChildCount() - 1;
                } else {
                    tempPosition = adjPosition;
                }

                holder.itemView.setOnTouchListener(new OnWrapperClickListener(TYPE.CENTER, holder.itemView,
                        adjPosition,
                        tempPosition));
                return;
            }
        }

        holder.itemView.setOnTouchListener(new OnWrapperClickListener(TYPE.FOOT, holder.itemView, adjPosition - adapterCount, position));
    }


    @Override
    public int getItemCount() {
        // 当前条目 = head条目 + 中间条目 + foot条目
        int count = 0;
        if (headView.getChildCount() > 0) {
            count += 1;
        }
        if (footView.getChildCount() > 0) {
            count += 1;
        }
        return count + originAdapter.getItemCount();
    }

    /*
     * 作者:史大拿
     * 创建时间: 10/19/22 3:56 PM
     * TODO 添加head布局
     */
    public void addHeadView(View view) {
        headView.addView(view);// 添加head
        notifyDataSetChanged();
    }

    /*
     * 作者:史大拿
     * 创建时间: 10/19/22 3:56 PM
     * TODO 添加foot布局
     */
    public void addFootView(View view) {
        footView.addView(view);// 添加head
        notifyDataSetChanged();
    }

    //    /*
//     * 作者:史大拿
//     * 创建时间: 10/19/22 3:57 PM
//     * TODO 删除头布局
//     */
    public void removeHeadView(View view) {
        if (isDelete(headView)) {
            headView.removeView(view);
            notifyDataSetChanged();
        }
    }

    public void removeHeadView(int position) {
        if (isDelete(headView)) {
            headView.removeViewAt(position);// 删除head
            notifyDataSetChanged();
        }
    }

    //    /*
//     * 作者:史大拿
//     * 创建时间: 10/19/22 3:58 PM
//     * TODO 删除foot布局
//     */
    public void removeFootView(View view) {
        if (isDelete(footView)) {
            footView.removeView(view);
            notifyDataSetChanged();
        }
    }

    public void removeFootView(int position) {
        if (isDelete(footView)) {
            footView.removeViewAt(position);// 删除head
            notifyDataSetChanged();
        }

    }

    // 是否删除
    public boolean isDelete(ViewGroup group) {
        if (group.getChildCount() == 0) return false;
        if (group.getChildCount() == 1) {
            showToast("至少保留一个 headView/footView(都删完会有BUG)。");
            return false;
        }
        return true;
    }

    public void showToast(@NonNull Object msg) {
        Toast.makeText(mContext, msg.toString(), Toast.LENGTH_SHORT).show();
    }

    private static class TempViewHolder extends RecyclerView.ViewHolder {

        public TempViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public interface OnAdapterListener {
        /*
         * 作者:史大拿
         * 创建时间: 10/19/22 4:36 PM
         * TODO 头部点击
         */
        void headViewClick(View view, int position);

        /*
         * 作者:史大拿
         * 创建时间: 10/19/22 4:37 PM
         * TODO 中间点击
         * @param position: 不包含头部尾部下标
         * @adapterPosition: 在列表中的位置
         */
        void centerViewClick(View view, int position, int adapterPosition);

        /*
         * 作者:史大拿
         * 创建时间: 10/19/22 4:37 PM
         * TODO 尾部点击
         * @param position: 不包含头部尾部下标
         * @adapterPosition: 在列表中的位置
         */
        void footViewClick(View view, int position, int adapterPosition);
    }

    public OnAdapterListener listener;

    public void seOnClickListener(OnAdapterListener listener) {
        this.listener = listener;
    }


    private class OnWrapperClickListener implements View.OnTouchListener {
        private final TYPE type;
        private final View view;
        private final int position;
        private final int adapterPosition;


        public OnWrapperClickListener(TYPE type, View view, int position, int adapterPosition) {
            this.type = type;
            this.view = view;
            this.position = position;
            this.adapterPosition = adapterPosition;
        }


        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getActionMasked() == MotionEvent.ACTION_UP && listener != null) {
                switch (type) {
                    case HEAD:
//                        if (view instanceof LinearLayout) {
//                            LinearLayout linearLayout = ((LinearLayout) view);
//                            for (int i = 0; i < linearLayout.getChildCount(); i++) {
//                                View view = linearLayout.getChildAt(i);
//                                float start = view.getY();
//                                float end = view.getY() + view.getHeight();
//                                Log.i("szjStart", start + "\tend:" + end + "\tvY:" + event.getY());
//                                if (event.getY() >= start && event.getY() <= end) {
//                                    listener.headViewClick(view, position);
//                                    break;
//                                }
//                            }
//                        }
                        SelectedInfo infoHead = getViewPosition(this.view, event);
                        if (infoHead != null) {
                            listener.headViewClick(infoHead.view, infoHead.position);
                        }

                        return true;
                    case CENTER:
                        listener.centerViewClick(this.view, position, adapterPosition);
                        break;
                    case FOOT:
                        SelectedInfo infoFoot = getViewPosition(this.view, event);
                        if (infoFoot != null) {
                            listener.footViewClick(infoFoot.view, infoFoot.position, adapterPosition);
                        }
                        break;
                }
            }
            return true;
        }

        private SelectedInfo getViewPosition(View viewGroup, MotionEvent event) {
            if (viewGroup instanceof LinearLayout) {
                LinearLayout linearLayout = ((LinearLayout) viewGroup);
                for (int i = 0; i < linearLayout.getChildCount(); i++) {
                    View view = linearLayout.getChildAt(i);
                    float start = view.getY();
                    float end = view.getY() + view.getHeight();
                    Log.i("szjStart", start + "\tend:" + end + "\tvY:" + event.getY());
                    if (event.getY() >= start && event.getY() <= end) {
                        return new SelectedInfo(view, i);
                    }
                }
            }
            return null;
        }

        public class SelectedInfo {
            // 选中的View
            public View view;
            // 选中的下标
            public int position;

            public SelectedInfo(View view, int position) {
                this.view = view;
                this.position = position;
            }
        }
    }

    enum TYPE {
        HEAD,
        CENTER,
        FOOT,
    }
}
